package com.och.mrcp.handler;

import com.och.mrcp.core.sip.model.SipMessage;
import com.och.mrcp.core.sip.model.SipRequest;
import com.och.mrcp.core.sip.model.SipResponse;
import com.och.mrcp.core.sip.transaction.SipTransaction;
import com.och.mrcp.core.sip.transaction.SipTransactionManager;
import com.och.mrcp.service.MediaSessionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

@Slf4j
@Component
public class SipMessageProcessorImpl extends SipMessageProcessor {
    
    private final MediaSessionManager mediaSessionManager;
    
    public SipMessageProcessorImpl(SipTransactionManager transactionManager, MediaSessionManager mediaSessionManager) {
        super(transactionManager);
        this.mediaSessionManager = mediaSessionManager;
    }
    
    @Override
    public void processMessage(SipMessage message, InetSocketAddress sender) {
        if (message instanceof SipRequest) {
            handleSipRequest((SipRequest) message, sender);
        } else if (message instanceof SipResponse) {
            handleSipResponse((SipResponse) message, sender);
        }
    }
    
    @Override
    protected void handleInviteRequest(SipRequest request, InetSocketAddress sender, SipTransaction transaction) {
        log.info("Handling INVITE request from {}", sender.getAddress().getHostAddress());
        
        try {
            // 1. 发送100 Trying（临时响应）
            SipResponse trying = SipResponse.createResponse(100);
            copyHeaders(request, trying);
            transaction.setProvisionalResponse(trying);
            transactionManager.updateTransaction(transaction);
            
            // 2. 通过媒体会话管理器处理INVITE，协商媒体会话
            SipResponse ok = mediaSessionManager.handleInviteRequest(request, sender);
            
            // 3. 设置最终响应
            transaction.setFinalResponse(ok);
            transactionManager.updateTransaction(transaction);
            
            log.info("INVITE request processed successfully");
            
        } catch (Exception e) {
            log.error("Failed to handle INVITE request: {}", e.getMessage(), e);
            
            // 发送错误响应
            SipResponse error = SipResponse.createResponse(500);
            copyHeaders(request, error);
            transaction.setFinalResponse(error);
            transactionManager.updateTransaction(transaction);
        }
    }
    
    @Override
    protected void handleAckRequest(SipRequest request, InetSocketAddress sender, SipTransaction transaction) {
        log.info("Handling ACK request from {}", sender.getAddress().getHostAddress());
        
        // 通知媒体会话管理器确认媒体会话
        mediaSessionManager.handleAckRequest(request, sender);
        
        // ACK不需要响应
        transaction.terminate();
        transactionManager.removeTransaction(transaction);
    }
    
    @Override
    protected void handleByeRequest(SipRequest request, InetSocketAddress sender, SipTransaction transaction) {
        log.info("Handling BYE request from {}", sender.getAddress().getHostAddress());
        
        // 通知媒体会话管理器终止媒体会话
        mediaSessionManager.handleByeRequest(request, sender);
        
        // 发送200 OK响应
        SipResponse ok = SipResponse.createResponse(200);
        copyHeaders(request, ok);
        
        transaction.setFinalResponse(ok);
        transactionManager.updateTransaction(transaction);
    }
    
    @Override
    protected void handleCancelRequest(SipRequest request, InetSocketAddress sender, SipTransaction transaction) {
        log.info("Handling CANCEL request from {}", sender.getAddress().getHostAddress());
        
        // 发送200 OK响应
        SipResponse ok = SipResponse.createResponse(200);
        copyHeaders(request, ok);
        
        transaction.setFinalResponse(ok);
        transactionManager.updateTransaction(transaction);
    }
    
    @Override
    protected void handleOptionsRequest(SipRequest request, InetSocketAddress sender, SipTransaction transaction) {
        log.info("Handling OPTIONS request from {}", sender.getAddress().getHostAddress());
        
        // 发送200 OK响应
        SipResponse ok = SipResponse.createResponse(200);
        copyHeaders(request, ok);
        // 添加Allow头部
        ok.addHeader("Allow", "INVITE, ACK, BYE, CANCEL, OPTIONS, REGISTER");
        
        transaction.setFinalResponse(ok);
        transactionManager.updateTransaction(transaction);
    }
    
    @Override
    protected void handleRegisterRequest(SipRequest request, InetSocketAddress sender, SipTransaction transaction) {
        log.info("Handling REGISTER request from {}", sender.getAddress().getHostAddress());
        
        // 发送200 OK响应
        SipResponse ok = SipResponse.createResponse(200);
        copyHeaders(request, ok);
        
        transaction.setFinalResponse(ok);
        transactionManager.updateTransaction(transaction);
    }
    
    @Override
    protected void handleUnknownRequest(SipRequest request, InetSocketAddress sender, SipTransaction transaction) {
        log.warn("Unknown SIP method: {} from {}", request.getMethod(), sender.getAddress().getHostAddress());
        
        // 发送501 Not Implemented响应
        SipResponse notImplemented = SipResponse.createResponse(501);
        copyHeaders(request, notImplemented);
        
        transaction.setFinalResponse(notImplemented);
        transactionManager.updateTransaction(transaction);
    }
    
    @Override
    protected void sendErrorResponse(InetSocketAddress recipient, Exception error) {
        log.error("Error occurred while processing SIP message: {}", error.getMessage());
        // 在实际实现中，这里应该发送错误响应
        // 但是由于UDP和TCP的发送方式不同，具体的发送逻辑由各自的处理器实现
    }
}
